package asia.yuanding.wechat.web.service.impl;

import asia.yuanding.wechat.system.constant.BusinessStatus;
import asia.yuanding.wechat.system.constant.SystemConstant;
import asia.yuanding.wechat.system.exception.BusinessException;
import asia.yuanding.wechat.system.util.ThreadUser;
import asia.yuanding.wechat.web.entity.ChatGroupUser;
import asia.yuanding.wechat.web.entity.User;
import asia.yuanding.wechat.web.entity.UserContact;
import asia.yuanding.wechat.web.mapper.ChatGroupUserMapper;
import asia.yuanding.wechat.web.service.ChatGroupUserService;
import asia.yuanding.wechat.web.service.UserContactService;
import asia.yuanding.wechat.web.service.UserService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import asia.yuanding.wechat.web.entity.ChatGroup;
import asia.yuanding.wechat.web.service.ChatGroupService;
import asia.yuanding.wechat.web.mapper.ChatGroupMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author YuanDing
* @description 针对表【chat_group】的数据库操作Service实现
* @createDate 2025-07-26 19:38:19
*/
@Service
public class ChatGroupServiceImpl extends ServiceImpl<ChatGroupMapper, ChatGroup>
    implements ChatGroupService{

    @Resource
    private ChatGroupUserService chatGroupUserService;

    @Resource
    private UserService userService;

    @Autowired
    private UserContactService userContactService;

    /**
     * 新建群聊
     * @param group
     * @throws BusinessException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createGroup(ChatGroup group) throws BusinessException {
        String currentUId = ThreadUser.getUId();
        group.setOwnerId(currentUId);
        List<String> uidList = group.getUidList();

        // 新建群聊不足2人
        if (uidList.isEmpty() || uidList.size() <= 2) {
            throw new BusinessException(BusinessStatus.LESS_THAN_TWO_USER.getCode(),  BusinessStatus.LESS_THAN_TWO_USER.getMessage());
        }

        // 群名为空则使用成员名称组成
        String GroupName = "";
        if (StrUtil.isBlankIfStr(group.getName())) {
            GroupName = userService.lambdaQuery().in(User::getUid, uidList)
                    .list().stream().limit(4).map(User::getNickname)
                    .collect(Collectors.joining("、"));
            group.setName(GroupName);
        }

        boolean save = this.save(group);
        if (!save) {
            throw new BusinessException("群组创建失败");
        }

        // 插入群组用户表
        Long id = group.getId();

        ArrayList<ChatGroupUser> chatGroupUserList = new ArrayList<>();
        ArrayList<UserContact> userContactList = new ArrayList<>();

        for (String uid : uidList) {
            // 群组用户表
            ChatGroupUser chatGroupUser = new ChatGroupUser();
            chatGroupUser.setUid(uid);
            chatGroupUser.setGroupId(id);
            if (Objects.equals(uid, currentUId)) {
                chatGroupUser.setIsOwner(1);
            }

            // 用户联系人表
            chatGroupUserList.add(chatGroupUser);

            UserContact userContact = new UserContact();
            userContact.setContactId(id.toString());
            userContact.setType(SystemConstant.UserContactType.GROUP);
            userContactList.add(userContact);
        }

        boolean result = chatGroupUserService.saveBatch(chatGroupUserList);
        boolean result2 = userContactService.saveBatch(userContactList);
        if (!result || !result2) {
            throw new BusinessException("群组创建失败");
        }


    }
}




